package com.example.bloodbankapplication.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.example.bloodbankapplication.R;
import com.example.bloodbankapplication.dialogfragment.CitiesDialogFragment;
import com.example.bloodbankapplication.dialogfragment.StatesDialogFragment;
import com.example.bloodbankapplication.entity.CitiesModel;
import com.example.bloodbankapplication.entity.StatesModel;
import com.example.bloodbankapplication.service.BloodBankService;

public class DonorRegistrationFragment extends BaseFragment implements OnTouchListener {
	private EditText etFirstName,etMiddleName,etLastname,etAge,etPhno,etEmailId,etState,etCity,etZipCode;
	private Spinner spBloodGroup;
	private RadioGroup rg;
	private Button btSubmit;
	private String instanceUrl,accesToken;
	private MyReceiver mReceiver;
	private final String ACTION = "DonorRegistrationFragment";
	private ArrayList<StatesModel> statesList;
	private ArrayList<CitiesModel> citiesList;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		//hideSoftKeyPad();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.donor_registration_fragment, null);
	}
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		
		mReceiver = new MyReceiver();
		instanceUrl = mPreferance.getString("Instance", "");
		accesToken  = mPreferance.getString("Access", "");
		
		
		
		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		etFirstName = (EditText) getView().findViewById(R.id.firstname);
		etMiddleName = (EditText) getView().findViewById(R.id.middlename);
		etLastname = (EditText) getView().findViewById(R.id.lastname);
		etAge = (EditText) getView().findViewById(R.id.age);
		etPhno = (EditText) getView().findViewById(R.id.Phone);
		etEmailId = (EditText) getView().findViewById(R.id.emailid);
		etState = (EditText) getView().findViewById(R.id.state);
		etCity = (EditText) getView().findViewById(R.id.city);
		etZipCode = (EditText) getView().findViewById(R.id.zipcode);
		
		etState.setOnTouchListener(this);
		etCity.setOnTouchListener(this);
		
		rg = (RadioGroup) getView().findViewById(R.id.gender);
		
		spBloodGroup = (Spinner) getView().findViewById(R.id.bgroup);
		
		if(!getConnectivity()){
			showPopUp(getActivity(), getResources().getString(R.string.nonetwork));
		}else{
		startProgressDialog();
		String statesURL ="https://www.whizapi.com/api/util/ui/in/indian-states-list.ashx?appkey=Tf3ZbMGA";
		Intent intent = new Intent(getActivity(),BloodBankService.class);
		intent.putExtra("URL", statesURL);
		intent.putExtra("Action", ACTION);
		intent.putExtra("Type", "States");
		intent.putExtra("Screen", "");
		getActivity().startService(intent);
		}
		
		
		btSubmit = (Button) getView().findViewById(R.id.submit);
		
		btSubmit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				if(etFirstName.getText().toString().trim().length()==0){
					showPopUp(getActivity(), "Please enter firstname.");
				}else if(etPhno.getText().toString().trim().length()==0){
					showPopUp(getActivity(), "please enter phone number.");
				}else if(etEmailId.getText().toString().trim().length()==0){
					showPopUp(getActivity(), "please enter EmailId.");
				}
				else{
				String fn = etFirstName.getText().toString();
				String ln = etLastname.getText().toString();
				String mn = etMiddleName.getText().toString();
				String age = etAge.getText().toString();
				String phone = etPhno.getText().toString();
				String email = etEmailId.getText().toString();
				String state = etState.getText().toString();
				String city = etCity.getText().toString();
				String zipcode = etZipCode.getText().toString();
				
				String bgroup = spBloodGroup.getSelectedItem().toString();
				
				String gender = null;
				
				if(rg.getCheckedRadioButtonId() == R.id.male){
					gender = "Male";
				}else{
					gender ="FeMale";
				}
				
				String registrationUrl = instanceUrl+"/services/data/v26.0/sobjects/DonarRegistration__c";
				
				
				Log.i("NCS","RegistrationUrl :"+registrationUrl);
				
				
				
				Intent intent = new Intent(getActivity(),BloodBankService.class);
				intent.putExtra("FN", fn);
				intent.putExtra("Ln", ln);
				intent.putExtra("MN", mn);
				intent.putExtra("Age", age);
				intent.putExtra("Phno", phone);
				intent.putExtra("BGroup", bgroup);
				intent.putExtra("State", state);
				intent.putExtra("City", city);
				intent.putExtra("Email", email);
				intent.putExtra("gender", gender);
				intent.putExtra("Zip", zipcode);
				intent.putExtra("Action", ACTION);
				intent.putExtra("URL", registrationUrl);
				intent.putExtra("AccessToken", accesToken);
				intent.putExtra("Screen", "Resgistration");
				intent.putExtra("Type", "");
				startProgressDialog();
				getActivity().startService(intent);
				

				}
			}
		});
		
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		MenuItem addAccount = menu.add("Logout");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS );
		addAccount.setIcon(R.drawable.logout); 
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 if(item.getTitle().equals("Logout")){
			 logout();
		 }
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onResume() {
		getActivity().registerReceiver(mReceiver, new IntentFilter(ACTION));
		super.onResume();
	}
	
	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	
	class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent intent) {
			
			
			
			stopProgressDialog();
			if(intent.getStringExtra("Category").equalsIgnoreCase("States")){
				statesList = new ArrayList<StatesModel>();
				try{
				JSONArray JArray = new JSONArray(intent.getStringExtra("Key"));
				int count = JArray.length();
				for(int i=0;i<count;i++){
					JSONObject jObject = JArray.getJSONObject(i);
					StatesModel model = new StatesModel();
					model.setId(jObject.getString("ID"));
					model.setName(jObject.getString("Name"));
					statesList.add(model);
				}
				
				}catch(Exception ex){
					
				}
			}
			else if (intent.getStringExtra("Category").equalsIgnoreCase("Cities")){
				Log.i("NCS","Cities Response :"+intent.getStringExtra("Key"));
				citiesList = new ArrayList<CitiesModel>();
				try{
				JSONArray cities = new JSONArray(intent.getStringExtra("Key"));
				int count = cities.length();
				for(int i=0;i<count;i++){
					JSONObject citiesObject = cities.getJSONObject(i);
					CitiesModel model = new CitiesModel();
					model.setName(citiesObject.getString("city"));
					citiesList.add(model);
				}
				
				}catch(Exception ex){
					
				}
			}
			else{
			showPopUp(getActivity(), getResources().getString(R.string.donormessage));}
			//Implement one Alert dialog for Successfully register message;
			
			// once we click the ok button to  clear all fields
			
		}
		
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		switch (v.getId()) {
		case R.id.state:
			
			if(event.getAction() == MotionEvent.ACTION_UP){
				
				StatesDialogFragment dialog = new StatesDialogFragment(statesList);
				dialog.show(getFragmentManager(), "");
			}
			
			break;
			
		case R.id.city:
			if(event.getAction() == MotionEvent.ACTION_UP){
				
				CitiesDialogFragment dialog = new CitiesDialogFragment(citiesList);
				dialog.show(getFragmentManager(), "");
			}
			
			break;

		default:
			break;
		}
		
		return false;
	}
	
	public void getVaues(String s1,String s2){
		
		etState.setText(s1);
		
		if(!getConnectivity()){
			showPopUp(getActivity(), getResources().getString(R.string.nonetwork));
		}else{
		startProgressDialog();
		String statesURL ="https://www.whizapi.com/api/util/ui/in/indian-city-by-state.ashx?stateid="+s2+"&appkey=Tf3ZbMGA";
		Intent intent = new Intent(getActivity(),BloodBankService.class);
		intent.putExtra("URL", statesURL);
		intent.putExtra("Action", ACTION);
		intent.putExtra("Type", "Cities");
		intent.putExtra("Screen", "");
		getActivity().startService(intent);
		}
		
		
	}
	
	public void getCitiesData(String name){
		etCity.setText(name);
	}

}
